import { useState } from 'react';

import { ReactComponent as Chevron } from '@/assets/images/shared/icon-chevron.svg';
import { AccordionProps } from '@/shared/interfaces';
import cn from 'classnames';

import cs from './Accordion.module.scss';

export const Accordion = ({
  item,
  isOpen,
  setIsOpen,
  className,
  titleClassName,
}: {
  item: AccordionProps;
  className?: string;
  titleClassName?: string;
  isOpen?: boolean;
  setIsOpen?: () => void;
}) => {
  const [isSelfOpen, setIsSelfOpen] = useState(false);
  const isSelfControlled = isOpen === undefined && setIsOpen === undefined;
  return ((isOpen?: boolean, setIsOpen?: () => void) => (
    <button className={cs.accordion} data-testid="accordion" onClick={setIsOpen} type="button">
      <div className={cs.header}>
        <div className={cn(cs.title, titleClassName)}>{item.title}</div>
        <div className={cn(cs.icon, isOpen && cs.active)}>
          <Chevron />
        </div>
      </div>
      <div className={cn(cs.body, isOpen && cs.active_item, className)}>{item.body}</div>
    </button>
  ))(isSelfControlled ? isSelfOpen : isOpen, isSelfControlled ? () => setIsSelfOpen(!isSelfOpen) : setIsOpen);
};
